#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
IR 枚举节点定义
"""

import ast
from dataclasses import dataclass, field
from typing import Any, Dict, List, Iterator, Optional
from ..base import IRNode
from .property import IRPropertyNode
from ...symbol_table import Symbol, SymbolKind


@dataclass
class IREnumNode(IRNode):
    """IR枚举节点"""

    name: str = field(default="")
    source_line: int = field(default=0)
    decorators: List[Dict[str, Any]] = field(default_factory=list)
    doc: str = field(default="")
    members: List["IRPropertyNode"] = field(default_factory=list)

    # 类属性
    node_type: str = "enum"

    def get_child_nodes(self) -> Iterator["IRNode"]:
        """获取所有子节点"""
        for member in self.members:
            yield member

        yield from super().get_child_nodes()

    def build_from_ast(self, node: ast.ClassDef) -> None:
        """从 AST 类定义节点构建 IR 枚举节点内容

        Args:
            node: AST 类定义节点
        """
        super().build_from_ast(node)

        # 提取枚举成员
        members = []
        for stmt in node.body:
            if isinstance(stmt, ast.Assign):
                for target in stmt.targets:
                    if isinstance(target, ast.Name):
                        member = IRPropertyNode(
                            name=target.id,
                            source_line=getattr(stmt, "lineno", 0),
                            parent=self,
                        )
                        # 设置枚举值作为扩展参数
                        member.set_extension_param(
                            "enum_value", ast.unparse(stmt.value) if stmt.value else ""
                        )
                        members.append(member)

        # 设置枚举节点属性
        self.name = node.name
        self.source_line = getattr(node, "lineno", 0)
        self.doc = ast.get_docstring(node) or ""
        self.members = members

    def new_symbol(self) -> "Symbol":
        """创建枚举的符号"""
        return Symbol(self.name, SymbolKind.ENUM, ir_node=self)

    def get_local_symbols(self) -> Iterator[Symbol]:
        """获取枚举中定义的所有本地符号

        Returns:
            本地符号的迭代器
        """
        # 枚举成员符号
        for member in self.members:
            symbol = member.get_symbol()
            if symbol:
                yield symbol
